package org.tinygroup.springwithtemplate3.impl;

import java.util.ArrayList;
import java.util.List;

import org.tinygroup.application.Application;
import org.tinygroup.application.ApplicationProcessor;
import org.tinygroup.logger.LogLevel;
import org.tinygroup.logger.Logger;
import org.tinygroup.logger.LoggerFactory;

/**
 * 基于Spring文件的Application
 * @author yancheng11334
 *
 */
public class SpringApplication implements Application {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(SpringApplication.class);

	private List<ApplicationProcessor> applicationProcessors = new ArrayList<ApplicationProcessor>();

	public void addApplicationProcessor(
			ApplicationProcessor applicationProcessor) {
		applicationProcessors.add(applicationProcessor);
		applicationProcessor.setApplication(this);
	}

	public List<ApplicationProcessor> getApplicationProcessors() {
		return applicationProcessors;
	}

	public void setApplicationProcessors(
			List<ApplicationProcessor> applicationProcessors) {
		this.applicationProcessors = applicationProcessors;
	}

	public void init() {
		for (ApplicationProcessor applicationProcessor : applicationProcessors) {
			LOGGER.logMessage(LogLevel.INFO, "应用处理器{}正在初始化...",
                    applicationProcessor.getClass());
			applicationProcessor.setApplication(this);
            applicationProcessor.init();
            LOGGER.logMessage(LogLevel.INFO, "应用处理器{}初始化完毕。",
                    applicationProcessor.getClass());
        }
	}

	public void start() {
		for (ApplicationProcessor applicationProcessor : applicationProcessors) {
            LOGGER.logMessage(LogLevel.INFO, "应用处理器{}正在启动...",
                    applicationProcessor.getClass());
            applicationProcessor.start();
            LOGGER.logMessage(LogLevel.INFO, "应用处理器{}启动完毕。",
                    applicationProcessor.getClass());
        }
	}

	public void stop() {
		for (int i = applicationProcessors.size() - 1; i >= 0; i--) {
            ApplicationProcessor processorLoader = applicationProcessors.get(i);
            LOGGER.logMessage(LogLevel.INFO, "应用处理器{}正在停止...",
                    processorLoader.getClass());
            processorLoader.stop();
            LOGGER.logMessage(LogLevel.INFO, "应用处理器{}停止完毕。",
                    processorLoader.getClass());
        }
	}

}
